package com.example.queryexpressdelivery_01.fragment;

import android.os.Bundle;
import android.util.ArrayMap;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.queryexpressdelivery_01.common.DeliveryDAL;
import com.example.queryexpressdelivery_01.common.HttpGetData;
import com.example.queryexpressdelivery_01.adapter.IndexRvAdapter;
import com.example.queryexpressdelivery_01.R;
import com.example.queryexpressdelivery_01.common.SharedViewModel;
import com.example.queryexpressdelivery_01.entity.FeedbackData;
import com.example.queryexpressdelivery_01.entity.TrackingResponse;
import com.example.queryexpressdelivery_01.entity.UserData;
import com.google.gson.Gson;
import com.youth.banner.Banner;
import com.youth.banner.adapter.BannerImageAdapter;
import com.youth.banner.holder.BannerImageHolder;
import com.youth.banner.indicator.CircleIndicator;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link IndexFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class IndexFragment extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private String sTitle;
    private String userid;
    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private Banner bannerIndexFragmentPic;
    private EditText edtIndexExpressNumber;
    private EditText edtIndexPhoneTail;
    private EditText edtIndexCompany;
    private Button btnIndexQuery;
    private Button btnIndexClear;
    private RecyclerView rvIndexResult;
    private ImageButton ibnIndexAdd;
    Gson gson = new Gson();
    IndexRvAdapter adapter = new IndexRvAdapter();
    TrackingResponse response = new TrackingResponse();
    public IndexFragment(String sTitle,String userid) {
        this.sTitle = sTitle;
        this.userid = userid;
        Bundle d1 = new Bundle();
        d1.putString("param1", sTitle);
        d1.putString("id",userid);
        this.setArguments(d1);
    }

    public String getTitle() {
        return sTitle;
    }
    public String getUserid() {
        return userid;
    }
    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment IndexFragment.
     */
    // TODO: Rename and change types and number of parameters
    public IndexFragment newInstance(String param1, String param2) {
        IndexFragment fragment = new IndexFragment(param1,param2);
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }
    public void onStart() {
        super.onStart();
        Banner banner = (Banner) bannerIndexFragmentPic;
        List list = new ArrayList();
        list.add(R.drawable.naobaijing);
        list.add(R.drawable.kfc);
        list.add(R.drawable.guojiaanquan);
        list.add(R.drawable.hefuping);
        list.add(R.drawable.sanguo);
        list.add(R.drawable.hepingjingying);
        //01
        bannerIndexFragmentPic.setAdapter(new BannerImageAdapter<Integer>(list) {
            @Override
            public void onBindView(BannerImageHolder holder, Integer data, int position, int size) {
                holder.imageView.setImageResource(data);


            }
        });
        bannerIndexFragmentPic.setIndicator(new CircleIndicator(requireActivity()));




        rvIndexResult.setLayoutManager(new LinearLayoutManager(getContext()));
        DeliveryDAL deliveryDAL = new DeliveryDAL(getContext());
        btnIndexQuery.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String num=  edtIndexExpressNumber.getText().toString().trim();
                String phone = edtIndexPhoneTail.getText().toString().trim();
                String company = edtIndexCompany.getText().toString().trim();
                if (!num.isEmpty() && !phone.isEmpty()){
                    List<Map<String,String>> expressInfo=new ArrayList<>();
                    String no = num+":"+phone;
                    String t = company.isEmpty()?null:company;
                    HttpGetData httpGetData = new HttpGetData(no,t,null);
                    String jsonResponse = httpGetData.QueryLogistics();
                    response = gson.fromJson(jsonResponse, TrackingResponse.class);
                    if (response.getStatus().equals("0")){  // 如果状态为0，说明单号数据正常
                        Map<String,String> status = new ArrayMap<>();
                        status.put("查询状态：","正常");

                        Map<String,String> number = new ArrayMap<>();
                        number.put("单号：",response.getResult().getNumber());
                        response.getResult().setNumber(response.getResult().getNumber()+":"+phone);

                        Map<String,String> type = new ArrayMap<>();
                        type.put("快递公司简称：",response.getResult().getType());

                        expressInfo.add(status);
                        expressInfo.add(number);
                        expressInfo.add(type);
                        if (!response.getResult().getList().isEmpty()){
                            for (int i=0;i<response.getResult().getList().size();i++){
                                Map<String,String> time = new ArrayMap<>();
                                time.put("时间：",response.getResult().getList().get(i).getTime());
                                Map<String,String> s = new ArrayMap<>();
                                s.put("状态：",response.getResult().getList().get(i).getStatus());
                                expressInfo.add(time);
                                expressInfo.add(s);
                            }
                        }
                    } else{
                        Map<String,String> status = new ArrayMap<>();
                        status.put("查询状态：",response.getMsg());
                        expressInfo.add(status);
                    }
                    adapter.setExpressList(expressInfo);
                    rvIndexResult.setAdapter(adapter);
                }else Toast.makeText(getContext(),"查询失败，快递单号与手机尾号为必填项！",Toast.LENGTH_SHORT).show();

            }
        });
        btnIndexClear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                edtIndexExpressNumber.setText("");
                edtIndexPhoneTail.setText("");
                edtIndexCompany.setText("");
            }
        });
        ibnIndexAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (response.getStatus()!=null){
                    if (response.getStatus().equals("0")){
                        Log.i("TAG","测试1");
                        UserData userData = deliveryDAL.queryById(Integer.parseInt(userid));
                        FeedbackData feedbackData;

                        if (userData!=null){
                            if (userData.getData()!=null){
                                feedbackData = gson.fromJson(userData.getData(), FeedbackData.class);
                            }else feedbackData = new FeedbackData();
                        }else {
                            feedbackData = new FeedbackData();
                        }
                        String[] array = response.getResult().getNumber().split(":");
                        FeedbackData.Trace trace = new FeedbackData.Trace();
                        trace.setNumber(array[0]);
                        trace.setPhone(array[1]);
                        trace.setType(response.getResult().getType());
                        feedbackData.setTrace(trace);
                        String result = gson.toJson(feedbackData);
                        UserData u = new UserData(userData.getId(),userData.getAccount(),userData.getPhone(),userData.getPassword(),
                                userData.getEmail(),result,userData.getLastlogintime(),userData.getStatus());
                        long ans =deliveryDAL.updateUser(u);
                        SharedViewModel model = new ViewModelProvider(requireActivity()).get(SharedViewModel.class);
                        model.setTrackingData(response);
                        if (ans!=0)Toast.makeText(getContext(),"添加成功",Toast.LENGTH_SHORT).show();
                        else Log.i("TAG","修改失败");
                    }else {
                        Log.i("TAG","单号状态异常，无法添加");
                        Toast.makeText(getContext(),"单号状态异常，无法添加",Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });
            }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_index, container, false);
        initView(view);
        return view;
    }

    private void initView(View v) {
        bannerIndexFragmentPic = (Banner) v.findViewById(R.id.bannerIndexFragmentPic);
        edtIndexExpressNumber = (EditText) v.findViewById(R.id.edtIndexExpressNumber);
        edtIndexPhoneTail = (EditText) v.findViewById(R.id.edtIndexPhoneTail);
        edtIndexCompany = (EditText) v.findViewById(R.id.edtIndexCompany);
        btnIndexQuery = (Button) v.findViewById(R.id.btnIndexQuery);
        btnIndexClear = (Button) v.findViewById(R.id.btnIndexClear);
        rvIndexResult = (RecyclerView) v.findViewById(R.id.rvIndexResult);
        ibnIndexAdd = (ImageButton) v.findViewById(R.id.ibnIndexAdd);
    }
}